import { ElMessageBox } from 'element-plus'
import { token } from '@/storage'
import { Session } from '@/utils/storage'

/**
 * 检查浏览器是否支持通知
 */
export const checkNotification = async () => {
  try {
    // 本次会话不再提示
    if (Session.get('NoNeedNotification')) return Promise.resolve('NoNeedNotification')

    // 没登陆
    if (!token.value) return Promise.resolve('NotPermission')

    // 延迟2秒
    await new Promise((resolve) => setTimeout(resolve, 2000))

    // 检查是否支持
    if ('Notification' in window) {
      const permission = Notification.permission
      if (permission === 'granted') {
        return Promise.resolve(permission)
      } else if (permission === 'default') {
        await ElMessageBox.confirm(
          '有审批消息时，系统可能会给你发送系统消息，是否去授权？',
          '系统通知提示',
          {
            confirmButtonText: '去授权',
            cancelButtonText: '暂时不需要',
            type: 'warning'
          }
        )
        await Notification.requestPermission()
      } else {
        return Promise.resolve(permission)
      }
    } else {
      return Promise.resolve('NotSupported')
    }
  } catch (e) {
    // 本次会话不再提示
    Session.set('NoNeedNotification', true)
  }
}
